package snafu.framework.states.literals;

import snafu.framework.view.Access;
import snafu.framework.view.View;
import snafu.framework.view.ViewFactory;

public abstract class StateLiteralView<T> implements StateLiteral<T>, View {
	
	/** The access type. */
	protected Access access;
	/** The original literal. */
	protected StateLiteralItself<T> literal;

	/**
	 * Instantiates a new view of the given literal with the given access.
	 * 
	 * @param access
	 *            the access type
	 * @param literal
	 *            the original literal
	 */
	public StateLiteralView(Access access, StateLiteralItself<T> literal) {
		this.access = access;
		this.literal = literal;
	}
	
	@Override
	public T getValue() {
		if (ViewFactory.class.isAssignableFrom(literal.getValue().getClass())) {
			return (T) ((ViewFactory<?>)literal.getValue()).createView(access);
		}
		return literal.getValue();
	}
	
	@Override
	public boolean equals(Object o) {
		if (!(o instanceof StateLiteral<?>))
			return false;
		
		Class<?>[] interfaces = this.getClass().getInterfaces();
		
		for (Class<?> clazz : interfaces) {
			if (clazz.isAssignableFrom(o.getClass()) && clazz.isAssignableFrom(this.getClass())
					&& StateLiteral.class.isAssignableFrom(clazz))
				return true;
		}
		
		return false;
	}
}
